<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { useNewsStore } from "@/store/modules/news";
import { watch } from "vue";
defineOptions({
  name: "BaseEditor"
});
const newsStore = useNewsStore();
const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(newsStore.valueHtml ? newsStore.valueHtml : "");
watch(
  () => valueHtml.value, // 监听的目标
  (newValue, oldValue) => {
    newsStore.valueHtml = newValue;
  }
);
const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "http://172.16.0.6:9000/api/common/newsUpload",
      fieldName: "file",
      maxFileSize: 10 * 1024 * 1024, // 2MB
      allowedFileTypes: ["image/jpeg", "image/png"], // 限制文件类型
      headers: {
        Authorization:
          "Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6Inh1ZGFkYSIsInVzZXJJZCI6ImE2NzZkYWZkNzVkYzExZWY4ZjUyMDAxNjNlMDEyMzA1IiwiZXhwIjoxNzI3Njc5NjQ2fQ.6ft7Qi_fu1Jcvk3aMB9PASIRnn7Hcrt53RwJ5gLpCCM"
      },
      customInsert(res, insertFn) {
        const imageUrl = res.data; // 获取图片 URL
        insertFn(imageUrl); // 插入图片
      }
    }
  }
};

const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="wangeditor">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      style="height: 500px; overflow-y: hidden"
      @onCreated="handleCreated"
    />
  </div>
  <div style="margin-top: 10px">
    <textarea
      v-model="valueHtml"
      readonly
      style="width: 100%; height: 200px; outline: none"
    />
  </div>
</template>
